import { createRouter, createWebHashHistory } from 'vue-router'
// 布局组件
import MainLayout from '@/layouts/MainLayout.vue'
// 页面组件
import Dashboard from '@/views/Dashboard.vue'
import DashboardSimple from '@/views/DashboardSimple.vue'
import Login from '@/views/Login.vue'
import AllInOne from '@/views/AllInOne.vue'
import DohBatch from "@/views/DohBatch.vue";
import DohSingle from "@/views/DohSingle.vue";
import DotBatch from "@/views/DotBatch.vue";
import DotSingle from "@/views/DotSingle.vue";
import DnssecSingle from "@/views/DnssecSingle.vue";
import DnssecBatch from "@/views/DnssecBatch.vue";
import CustomScan from "@/views/CustomScan.vue";
import Self from "@/views/Self.vue";
import Profile from "@/views/Profile.vue";
import ProfileTest from "@/views/ProfileTest.vue";
import CustomScanManager from "@/views/CustomScanManager.vue";
import AuthTest from "@/views/AuthTest.vue";
import AvatarTest from "@/views/AvatarTest.vue";
import { auth } from '@/utils/auth';

const routes = [
    // 登录页面 - 独立布局，不包含导航栏
    {
        path: '/login',
        name: 'Login',
        component: Login
    },
    
    // 主应用路由 - 使用MainLayout布局
    {
        path: '/',
        component: MainLayout,
        meta: { requiresAuth: true },
        children: [
            {
                path: '',
                redirect: '/dashboard'
            },
            {
                path: 'dashboard',
                name: 'Dashboard',
                component: DashboardSimple,
                meta: { requiresAuth: true }
            },
            {
                path: 'allInOne',
                name: 'AllInOne',
                component: AllInOne,
                meta: { requiresAuth: true }
            },
            {
                path: 'dohBatch',
                name: 'DohBatch',
                component: DohBatch,
                meta: { requiresAuth: true }
            },
            {
                path: 'dohSingle',
                name: 'DohSingle',
                component: DohSingle,
                meta: { requiresAuth: true }
            },
            {
                path: 'dotBatch',
                name: 'DotBatch',
                component: DotBatch,
                meta: { requiresAuth: true }
            },
            {
                path: 'dotSingle',
                name: 'DotSingle',
                component: DotSingle,
                meta: { requiresAuth: true }
            },
            {
                path: 'dnssecSingle',
                name: 'DnssecSingle',
                component: DnssecSingle,
                meta: { requiresAuth: true }
            },
            {
                path: 'dnssecBatch',
                name: 'DnssecBatch',
                component: DnssecBatch,
                meta: { requiresAuth: true }
            },
            {
                path: 'self',
                name: 'Self',
                component: Self,
                meta: { requiresAuth: true }
            },
            {
                path: 'customScan',
                name: 'CustomScan',
                component: CustomScan,
                meta: { requiresAuth: true }
            },
            {
                path: 'custom-scan',
                name: 'CustomScanManager',
                component: CustomScanManager,
                meta: { requiresAuth: true }
            },
            {
                path: 'profile',
                name: 'Profile',
                component: Profile,
                meta: { requiresAuth: true }
            },
            {
                path: 'auth-test',
                name: 'AuthTest',
                component: AuthTest,
                meta: { requiresAuth: true }
            },
            {
                path: 'avatar-test',
                name: 'AvatarTest',
                component: AvatarTest,
                meta: { requiresAuth: true }
            }
        ]
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

// 加强版路由守卫 - 增加详细调试信息
router.beforeEach((to, from, next) => {
    console.log(`%c🛡️ 路由守卫触发`, 'color: #2196F3; font-weight: bold')
    console.log(`📍 路由变化: ${from.path || '(首次访问)'} → ${to.path}`)
    console.log(`🎯 目标路由:`, to)
    
    // 首先检查localStorage中的原始数据
    const rawToken = localStorage.getItem('token')
    const rawUser = localStorage.getItem('user')
    console.log(`💾 localStorage状态: token=${!!rawToken}, user=${!!rawUser}`)
    
    // 检查路由是否需要认证
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
    console.log(`🔐 路由是否需要认证:`, requiresAuth)
    
    if (requiresAuth) {
        console.log(`%c🔍 开始认证检查`, 'color: #FF9800; font-weight: bold')
        
        // 详细的认证状态检查
        const token = auth.getToken()
        const user = auth.getUser()
        console.log(`📄 Token存在:`, !!token)
        console.log(`👤 User存在:`, !!user)
        
        if (token) {
            console.log(`📄 Token长度:`, token.length)
            try {
                const isExpired = auth.isTokenExpired(token)
                console.log(`⏰ Token是否过期:`, isExpired)
                
                if (isExpired) {
                    console.log(`%c❌ Token已过期，清除认证信息`, 'color: #F44336')
                    auth.clearAuth()
                }
            } catch (error) {
                console.log(`%c❌ Token解析失败:`, 'color: #F44336', error)
                auth.clearAuth()
            }
        }
        
        // 最终认证判断
        const isAuthenticated = auth.isAuthenticated()
        console.log(`%c✅ 最终认证结果: ${isAuthenticated}`, isAuthenticated ? 'color: #4CAF50' : 'color: #F44336')
        
        if (!isAuthenticated) {
            console.log(`%c🔄 重定向到登录页`, 'color: #FF5722; font-weight: bold')
            console.log(`📝 保存重定向目标:`, to.fullPath)
            
            // 清除可能存在的无效认证信息
            auth.clearAuth()
            
            // 未登录，重定向到登录页
            next({
                path: '/login',
                query: { redirect: to.fullPath } // 保存目标路由，登录后跳转
            })
            return
        } else {
            console.log(`%c✅ 认证通过，允许访问`, 'color: #4CAF50; font-weight: bold')
        }
    } else {
        console.log(`%c🔓 路由无需认证`, 'color: #9E9E9E')
        
        // 如果已登录用户访问登录页，重定向到首页
        if (to.path === '/login' && auth.isAuthenticated()) {
            console.log(`%c🔄 已登录用户访问登录页，重定向到首页`, 'color: #2196F3')
            next({ path: '/dashboard' })
            return
        }
    }
    
    console.log(`%c🚀 允许路由跳转`, 'color: #4CAF50; font-weight: bold')
    next()
})

// 路由错误处理
router.onError((error) => {
    console.error('路由错误:', error)
})

export default router